package com.meizi.core.tool.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.meizi.core.tool.status.BaseStatus;
import com.meizi.core.tool.status.IStatus;
import lombok.Data;
import org.apache.http.HttpStatus;

import java.util.HashMap;
import java.util.Map;

/**
 * @author meizi
 * @email enjoymeizi@gmail.com
 * @date 2020/11/26 12:47
 */
@Data
public class R extends HashMap<String, Object> {

    public R() {
        put("code", 0);
        put("msg", "success");
    }

    public R(int code, String msg, Object data) {
        put("code", code);
        put("msg", msg);
        put("data", data);
    }

    public static R error(IStatus iStatus) {
        return error(iStatus.getCode(),iStatus.getMsg());
    }

    public R of(int code, String msg, Object data) {
        return new R(code, msg, data);
    }

    public static   R  ofStatus(IStatus status) {
        return new R(status.getCode(), status.getMsg(), null);
    }

    public static R ofStatus(IStatus status, Object data) {
        return new R(status.getCode(), status.getMsg(), data);
    }

    public static R ofSuccess() {
        return ofStatus(BaseStatus.SUCCESS);
    }

    public static R ofSuccess(Object data) {
        return ofStatus(BaseStatus.SUCCESS, data);
    }

    public static R error() {
        return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常，请联系管理员");
    }

    public static R error(String msg) {
        return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
    }

    public static R error(int code, String msg) {
        R r = new R();
        r.put("code", code);
        r.put("msg", msg);
        return r;
    }


    public static R ok(String msg) {
        R r = new R();
        r.put("msg", msg);
        return r;
    }

    public static R ok(Map<String, Object> map) {
        R r = new R();
        r.putAll(map);
        return r;
    }

    public static R ok() {
        return new R();
    }

    @Override
    public R put(String key, Object value) {
        super.put(key, value);
        return this;
    }

    public int getCode() {
        return (int)get("code");
    }

    public R setData(Object data){
        put("data",data);
        return this;
    }
    public <T> T getData(TypeReference<T> typeReference){
        Object data = get("data");
        String s = JSON.toJSONString(data);
        T t = JSON.parseObject(s, typeReference);
        return t;
    }
}
